//index.js
//获取应用实例
var app = getApp();
var requestService = require('../../utils/requestService.js');
var qrCodeUtil = require('../../utils/qrCodeUtil.js');
Page({
  data: {
    scale: 10,
    latitude: 0,
    longitude: 0,
    markers: [],
    windowWidth:0,/**屏幕宽度*/
    windowHeight:0,/**屏幕高度*/
    currMaker:{},/**选中标记点后存储的当前标记点信息*/
    //地图的宽高
    mapHeight: '100%',/**地图高度*/
    mapWidth: '100%',/**地图宽度*/
    mapTop: '0',/**地图距离顶端高度*/
    //站点简要显示的视图的属性
    stationInfo: {
        show: true,
        height: '25%',
        width: '100%',
        topLineHeight: "0rpx",
        bottomLineHeight: "0rpx",
        stationName:'',/**站点名称*/
        totalCharger: 0,/**充电桩总数*/
        idleTotalCharger: 0,/**空闲充电桩总数*/
        parkingAddress:'',/**站点地址*/
        distance:'未知'  /**到站点距离*/
    },
  },
  // 页面加载
  onLoad: function (options) {
    // 2.获取并设置当前位置经纬度
    var that=this;
    // 1.获取定时器，用于判断是否已经在计费
      wx.getLocation({
      type: "gcj02",
      success: (res) => {
        this.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
      },
      fail:function(){
        wx.showModal({
          title: '提示',
          content: '获取位置信息失败，请打开GPS',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            }
          }
        })
      }
    });
    // 3.设置地图控件的位置及大小，通过设备宽高定位
        this.setData({
          windowWidth: wx.getStorageSync("kScreenW"),
          windowHeight: wx.getStorageSync("kScreenH"),
          controls: [
          {
            id: 1,
            iconPath: '../images/scanqrcode.png',
            position: {
              left: 0,
              top: wx.getStorageSync("kScreenH") - 50,
              width:  wx.getStorageSync("kScreenW"),
              height: 50
            },
            clickable: true
          },
          {
            id: 2,
            iconPath: '../images/ico_menu.png',
            position: {
              left: wx.getStorageSync("kScreenW") - 58,
              top: wx.getStorageSync("kScreenH") - 146,
              width: 73,
              height: 63
            },
            clickable: true
          },{
            id: 3,
            iconPath: '../images/ico_restore.png',
            position: {
              left: 20,
              top: wx.getStorageSync("kScreenH") - 133,
              width: 50,
              height: 50
            },
            clickable: true
          },{
            id: 4,
            iconPath: '../images/ico_center.png',
            position: {
              left: wx.getStorageSync("kScreenW") / 2-23,
              top: wx.getStorageSync("kScreenH") / 2 - 51,
              width: 50,
              height: 50
            },
            clickable: true
          }]
        })

    // 4.请求服务器，显示附近的充電站，用marker标记
      requestService.sendGetRequest("/station/markers",null,function(result){
        var stations=result.data.resData;
        var markers=[];
        var index=0;
          stations.forEach(function (item) {
              var maker={};
              maker.id=index;
              maker.latitude=item.latitude;
              maker.longitude=item.longitude;
              maker.title=item.stationName;
              maker.iconPath="../images/ico_busy.png";
              maker.stationId=item.stationId;
              maker.width=50;
              maker.height=50;
              markers.push(maker);
              index++;
          });
          that.setData({
              markers:markers
          })
      },function(){

      })
  },
  // 页面显示
  onShow: function () {
    // 1.创建地图上下文，移动当前位置到地图中心
    this.mapCtx = wx.createMapContext("myMap");
    this.movetoPosition()
  },
  // 地图控件点击事件
  bindcontroltap: function (e) {
    // 判断点击的是哪个控件 e.controlId代表控件的id，在页面加载时的第3步设置的id
    switch (e.controlId) {
      // 点击立即充电，判断当前是否正在计费
      case 1:
        this.scanChargingCode(e.controlId);
        break;
      // 点击头像控件，跳转到个人中心
      case 2: wx.navigateTo({
        url: '../my/index'
      });
        break;
      // 点击定位控件
      case 3:
      this.movetoPosition();
        break;
      // 点击定位控件
      case 5:
        this.stopCharging();
        break;
      default:
        break;
    }
  },
  // 地图标记点击事件，连接用户位置和点击的充电站位置
  bindmarkertap: function (e) {
      let _markers = this.data.markers;
      let markerId = e.markerId;
      let currMaker = _markers[markerId];
      let that=this;
      // 请求服务器，获取点击的站点简介信息
      let stationId=currMaker.stationId;
      requestService.sendGetRequest("/station/abstract/"+stationId,null,function(result){
          var stationAbstract=result.data.resData;
          that.setData({
              currMaker:currMaker,
              "stationInfo.show": true,
              mapHeight:"75%",
              "stationInfo.stationName": stationAbstract.stationName,
              "stationInfo.totalCharger": stationAbstract.totalCharger,
              "stationInfo.idleTotalCharger": stationAbstract.idleTotalCharger,
              "stationInfo.parkingAddress": stationAbstract.parkingAddress
          })
      },function(){
          wx.showModal({
              title: '提示',
              content: '获取站点信息异常',
              showCancel: false
          })
      })
      //请求服务器，获取到站点的距离
      requestService.sendGetRequest("/station/distance",
          {'fromLat':that.data.latitude,'fromLng':that.data.longitude,'toLat':currMaker.latitude,'toLng':currMaker.longitude},function(result){
              var distance=result.data.resData;
              that.setData({
                  "stationInfo.distance": distance
              })
      })

  },
  // 定位函数，移动位置到地图中心
  movetoPosition: function () {
    this.mapCtx.moveToLocation();
  },
  scanChargingCode: function (controlId){
      const that=this;
      requestService.sendGetRequest("/charger/userChargState",null,function(result){
          const chargerProgress=result.data.resData;
          if(chargerProgress!=null && (chargerProgress.chargeStatus=="1" || chargerProgress.chargeStatus=="2")){
                // 当前正在充电或已预约跳转到计费页面
              wx.navigateTo({
                  url: '../charge/index?address='+chargerProgress.address
              })
          }else{
              // 没有在计费就扫码
              wx.scanCode({
                  scanType: "qrCode",
                  success: (res) => {
                  // 请求服务器开起充电
                  let qrCodeRes=res.result;

              let qrCode=qrCodeUtil.decompose(res.result);
              console.log(qrCode);
              if(qrCode){
                  //that.startCharging(qrCode);
                  wx.navigateTo({
                      url: '../charge/prepare?qrCode='+qrCode
                  })
              }else{
                  wx.showModal({
                      title: '提示',
                      content: '扫描二维码失败',
                      showCancel: false
                  })
              }
          },
              fail: function() {
                  wx.showModal({
                      title: '提示',
                      content: '扫描二维码失败',
                      showCancel: false,
                      success: function (res) {
                          if (res.confirm) {
                              console.log('用户点击确定')
                          }
                      }
                  })
              }
          })
          }
      });

  },
  /**请求服务器开始充电*/
  startCharging: function (qrCode){
      requestService.sendPostRequest("/charger/scanCharge",{'qrCode':qrCode},function(result){
          const resultData=result.data;
          if(resultData.resCode==0){
              wx.navigateTo({
                  url: '../charge/index'
              })
          }else{
              wx.showModal({
                  title: '提示',
                  content: resultData.message,
                  showCancel: false
              })
          }
      },function(result){
          wx.showModal({
              title: '提示',
              content: '失败',
              showCancel: false
          })
      })
  },
    //地图点击事件，隐藏下面电桩详情
    mapBindTap:function () {
        this.setData({
          "stationInfo.show": false,
           mapHeight:"100%"
        })
    },
    //导航
    gotoSation:function () {
       let currMaker = this.data.currMaker;
       let stationInfo=this.data.stationInfo;
        wx.openLocation({
            longitude: Number(currMaker.longitude),
            latitude: Number(currMaker.latitude),
            scale: 18,
            name: stationInfo.stationName,
            address: stationInfo.parkingAddress
        })
    },
    //站点详情
    stationDetail:function () {
      let currMaker=this.data.currMaker;
      let stationInfo=this.data.stationInfo;
        wx.navigateTo({
            url: '../station/index?stationId='+currMaker.stationId+"&stationName="+stationInfo.stationName+"&parkingAddress="+stationInfo.parkingAddress+"&distance="+stationInfo.distance
        });
        /*wx.navigateTo({url:'../my/index'})*/
    }
})
